<?php

/**
 * Google Weather Api
 * 谷歌天气预报接口类 
 */
class WeatherApi
{
	private $xml;

	public function __construct($city = 'beijing')
	{
		$string = @file_get_contents("http://www.google.com/ig/api?hl=zh-cn&weather=$city");
		$content = iconv("GB18030", "utf-8", $string);
		//$content = mb_convert_encoding($string, 'UTF-8', 'GBK');

		$this->xml = simplexml_load_string($content);
	}

	/**
	 * 获取当前实时天气信息
	 *
	 */
	public function get_current_weather()
	{
		$current_conditions = $this->xml->weather->current_conditions;
		if (empty($current_conditions))
		{
			return false;
		}

		$condition = $current_conditions->condition->attributes();
		$temp_f = $current_conditions->temp_f->attributes();
		$temp_c = $current_conditions->temp_c->attributes();
		$humidity = $current_conditions->humidity->attributes();
		$icon = $current_conditions->icon->attributes();
		$wind = $current_conditions->wind_condition->attributes();

		return $weather = array(
				'condition' => (string)$condition,
				'temp_f'    => (int)$temp_f,
				'temp_c'    => (int)$temp_c,
				'humidity'  => (string)$humidity,
				'icon'      => (string)$icon,
				'wind'      => (string)$wind
			);
	}

	/**
	 * 获取当前的，未来三天的天气情况
	 *
	 */
	public function get_forecast_weather()
	{
		$forecast_conditions = $this->xml->weather->forecast_conditions;
		if (empty($forecast_conditions))
		{
			return false;
		}

		foreach($forecast_conditions as $val)
		{
			$forecast[] = array(
				'day_of_week' => (string)$val->day_of_week['data'],
			    'low'         => (int)$val->low['data'],
			    'high'        => (int)$val->high['data'],
			    'icon'        => (string)$val->icon['data'],
			    'condition'   => (string)$val->condition['data']
			);
		}

		return $forecast;
	}

	/**
	 * 新浪天气api
	 * sinaWeatherApi
	 */
	public function sinaWeather($city = '北京')
	{
		$city = urlencode(iconv('utf-8', 'gb2312', $city));
		$api = "http://php.weather.sina.com.cn/xml.php?city=$city&password=DJOYnieT8234jlsK&day=0";
		$string = file_get_contents($api);
		$xml = simplexml_load_string($string);
		$xml = $xml->weather;

		return $xml;
	}
}
?>
